package config;

import com.jfinal.config.*;
import com.jfinal.core.JFinal;
import com.jfinal.ext.interceptor.POST;
import com.jfinal.json.FastJsonFactory;
import com.jfinal.kit.Prop;
import com.jfinal.kit.PropKit;
import com.jfinal.plugin.activerecord.ActiveRecordPlugin;
import com.jfinal.plugin.activerecord.dialect.PostgreSqlDialect;
import com.jfinal.plugin.druid.DruidPlugin;
import com.jfinal.template.Engine;
import controller.HelloController;
import model._MappingKit;

/**
 * @Author: Raymond
 * @Date: 2020/7/13 16:23
 * @Description:
 */
public class AppConfig extends JFinalConfig {

    static Prop p;

    /**
     * PropKit.useFirstFound(...) 使用参数中从左到右最先被找到的配置文件
     * 从左到右依次去找配置，找到则立即加载并立即返回，后续配置将被忽略
     */

    static void loadConfig() {
        if (p == null) {
            p = PropKit.useFirstFound("config.txt");
        }
    }
    @Override
    public void configConstant(Constants me) {
        loadConfig();
        me.setDevMode(p.getBoolean("devMode", false));
        me.setInjectDependency(true);
        me.setInjectSuperClass(false);
        me.setJsonFactory(new FastJsonFactory());
        me.setEncoding("UTF8");
        me.setJsonDatePattern("yyyy-MM-dd HH:mm");
    }
    @Override
    public void configRoute(Routes routes) {
        // 设置了一个baseViewPath
        //routes.setBaseViewPath("/webapp");
        // 添加路由
        routes.add("/detil", HelloController.class,"/index");
    }
    @Override
    public void configEngine(Engine engine) {
        //热启动
        engine.setDevMode(true);
        Engine.setFastMode(true);
        //配置页面的路径
        engine.addSharedObject("context", JFinal.me().getContextPath());
    }
    @Override
    public void configPlugin(Plugins me) {
        //采用阿里的druid连接池
        DruidPlugin druidPlugin = new DruidPlugin(p.get("jdbcUrl"), p.get("username"), p.get("password").trim());
        me.add(druidPlugin);
        //ActiveRecordPlugin插件
        ActiveRecordPlugin arp = new ActiveRecordPlugin(druidPlugin);
        //添加sql模板
        arp.addSqlTemplate("all.sql");
        ServiceMapping.mapping(arp);
        //设置方言
        arp.setDialect(new PostgreSqlDialect());
        _MappingKit.mapping(arp);
        me.add(arp);
    }

    public static DruidPlugin createDruidPlugin() {
        loadConfig();
        //创建连接
        return new DruidPlugin(p.get("jdbcUrl"), p.get("username"), p.get("password").trim());
    }
    @Override
    public void configInterceptor(Interceptors interceptors) {
        //interceptors.add(new POST());
    }
    @Override
    public void configHandler(Handlers handlers) {
    }
}
